package com.xindaoapp.happypet.fragments;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.xindao.photonics.fragments.manager.BaseFragment;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.adapter.ShoppingCartAdapter;
import com.xindaoapp.happypet.bean.ShoppingCartInfo;
import com.xindaoapp.happypet.shop.ui.ProductDetailActivity;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;

/**
 * 购物车
 * 
 * @author chenghao
 * 
 */
public class ShoppingCartFragment extends BaseFragment {
    private ListView mListView;
    private View mNoDataView;
    /** 去结算 */
    private Button mBtnClearing;
    /** 全选 */
    private View mCheckAll;
    private ArrayList<ShoppingCartInfo> mList;
    private ShoppingCartAdapter mAdapter;
    // 订单页面查看购物车时的商品id记录
    private String recids;

    /** 是否只展示不做处理 */
    private boolean isOnlyShowProduct;
    /** 是否删除购物车商品 */
    private boolean isDeleteProduct = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.layout_shoppingcart, container, false);
    }

    @Override
    protected void initViews(View view) {
        super.initViews(view);
        if (null != getArguments()) {
            isOnlyShowProduct = getArguments().getBoolean(Constants.KEY_ONLY_SHOW_PRODUCT);
            recids = getArguments().getString(Constants.KEY_RECID);
        }
        if (isOnlyShowProduct) {
            setTabTitle("商品清单");
            view.findViewById(R.id.bottom).setVisibility(View.GONE);
            getActivity().getWindow().getDecorView().findViewById(R.id.right)
                    .setVisibility(View.GONE);
        }
        mNoDataView = view.findViewById(R.id.no_data);
        mListView = (ListView) view.findViewById(R.id.listview);
        mBtnClearing = (Button) view.findViewById(R.id.clearing);
        mCheckAll = view.findViewById(R.id.check_all);
    }

    @Override
    protected boolean showRightView() {
        return false;
    }

    @Override
    protected void initEvents() {
        super.initEvents();
        mCheckAll.setOnClickListener(mOnClickListener);
        mBtnClearing.setOnClickListener(mOnClickListener);
    }

    // Screen右侧删除按钮
    @Override
    protected void setRightViewListener(View view) {
        super.setRightViewListener(view);
        view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(getActivity()).setTitle("确认").setMessage("是否确定删除？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                isDeleteProduct = true;
                                deleteShoppingCart();
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();
            }
        });
    }

    private String getRecId() {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < mList.size(); i++) {
            ShoppingCartInfo info = mList.get(i);
            if (info.isChecked && sb.length() == 0) {
                sb.append(info.rec_id);
            } else if (info.isChecked) {
                sb.append(",");
                sb.append(info.rec_id);
            }
        }
        return sb.toString();
    }

    /**
     * 删除购物车
     */
    private void deleteShoppingCart() {
        if (getProductCount() == 0) {
            Toast.makeText(getActivity(), "当前无选中的商品！！", Toast.LENGTH_SHORT).show();
            return;
        }

        getMoccaApi().deleteShoppingCart(UserState.getUserUid(), getRecId(),
                new IRequest<Boolean>() {

                    @Override
                    public void request(Boolean t) {
                        if (t) {

                            // onLoadData();
                            String[] recids = getRecId().split(",");
                            for (String recid : recids) {
                                for (ShoppingCartInfo info : mList) {
                                    if (info.rec_id.equals(recid)) {
                                        mList.remove(info);
                                        break;
                                    }
                                }
                            }
                            mAdapter.resetList(mList);
                            mAdapter.isDeleteProduct(true);
                            mAdapter.notifyDataSetChanged();
                            resetProductCount();
                            Toast.makeText(getActivity(), "删除成功！！", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(Constants.DELETE_CART);
                            intent.putExtra("goods_number", getGoodsAllNum());
                            getActivity().sendBroadcast(intent);
                        } else {
                            Toast.makeText(getActivity(), "删除失败！！", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private final OnClickListener mOnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            // 全选
                case R.id.check_all:
                    if (mCheckAll.isSelected()) {
                        mCheckAll.setSelected(false);
                    } else {
                        mCheckAll.setSelected(true);
                    }
                    parseShoppingCartList();
                    resetProductCount();
                    break;
                // 结算
                case R.id.clearing:
                    if (getProductCount() == 0) {
                        Toast.makeText(getActivity(), "购物车没有选中商品！！", Toast.LENGTH_SHORT).show();
                    } else {
                        Bundle bundle = new Bundle();
                        // bundle.putFloat(Constants.KEY_PRODUCT_PRICE, getProductPrice());
                        // int weight = 0;
                        // for (int i = 0; i < mList.size(); i++) {
                        // weight += mList.get(i).goods_weight;
                        // }
                        Constants.REC_ID = getRecId();
                        Constants.ALLPRICE = getProductPrice();
                        // Address.tittle = ;
                        // bundle.putInt(Constants.KEY_SHOPPING_CART_WEIGHT, weight);
                        // bundle.putString(Constants.KEY_RECID, getRecId());
                        // bundle.putSerializable(Constants.KEY_SHOPPING_CART_LIST, mList);
                        startFragment(new WriteOrderFragment(), bundle);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    // 初始化商品列表数据
    private void parseShoppingCartList() {
        if (mCheckAll.isSelected()) {
            for (ShoppingCartInfo info : mList) {
                info.isChecked = true;
            }
        } else {
            for (ShoppingCartInfo info : mList) {
                info.isChecked = false;
            }
        }
        if (null != mAdapter) {
            mAdapter.isDeleteProduct(false);
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onLoadData() {
        super.onLoadData();
        getMoccaApi().getShoppingCart(UserState.getUserUid(),
                new IRequest<ArrayList<ShoppingCartInfo>>() {

                    @SuppressLint("NewApi")
                    @Override
                    public void request(ArrayList<ShoppingCartInfo> t) {
                        if (null == getActivity()) {
                            return;
                        }
                        // 加载服务数据
                        if (null != t) {
                            mList = t;
                            if (null == mAdapter) {
                                // 获取到底部的高度
                                View bottomView = getView().findViewById(R.id.bottom);
                                View view = new View(getActivity());
                                // view.setAlpha(0);
                                android.widget.AbsListView.LayoutParams params =
                                        new android.widget.AbsListView.LayoutParams(
                                                LayoutParams.MATCH_PARENT, bottomView
                                                        .getLayoutParams().height);
                                view.setLayoutParams(params);
                                // 初始化自定义的下拉刷新view
                                mListView.addFooterView(view, null, false);
                                // 初始化购物车adapter数据
                                mAdapter =
                                        new ShoppingCartAdapter(getActivity(), t,
                                                new IRequest<Integer>() {
                                                    @Override
                                                    public void request(Integer t) {
                                                        resetProductCount();
                                                    }
                                                }, isOnlyShowProduct, recids);

                                mListView.setAdapter(mAdapter);
                            } else {
                                mAdapter.resetList(t);
                                mAdapter.isDeleteProduct(true);
                                mAdapter.notifyDataSetChanged();
                            }
                            resetProductCount();
                            onDataArrived(true);

                            // Intent intent = new Intent(Constants.DELETE_CART);
                            // intent.putExtra("goods_number", getGoodsAllNum());
                            // getActivity().sendBroadcast(intent);
                            // 加载缓存数据
                        } else {
                            mNoDataView.setVisibility(View.VISIBLE);
                            onDataArrived(false);
                        }
                        if (!isOnlyShowProduct) {
                            mListView.setOnItemClickListener(new OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> arg0, View view,
                                        int position, long arg3) {
                                    Intent intent =
                                            new Intent(getActivity(), ProductDetailActivity.class);
                                    intent.putExtra(Constants.KEY_GOODS_ID,
                                            mList.get(position).goods_id);
                                    startActivity(intent);

                                    // Intent intent =
                                    // new Intent(getActivity(), ProductDetailActivity1.class);
                                    // intent.putExtra("productId", mList.get(position).goods_id);
                                    // startActivity(intent);
                                }
                            });
                        }
                    }
                });
    }

    // 获得待提交商品的个数
    private int getProductCount() {

        if (mList == null) {
            return 0;
        }
        int count = 0;
        for (ShoppingCartInfo info : mList) {
            if (info.isChecked) {
                count++;
            }
        }
        return count;
    }

    private int getGoodsNum() {
        if (mList == null) {
            return 0;
        }
        int count = 0;
        for (ShoppingCartInfo info : mList) {
            if (info.isChecked) {
                count = count + info.goods_number;
            }
        }
        return count;
    }

    private int getGoodsAllNum() {
        if (mList == null) {
            return 0;
        }
        int count = 0;
        for (ShoppingCartInfo info : mList) {
            count = count + info.goods_number;
        }
        return count;
    }

    private void resetProductCount() {
        int count = getProductCount();
        if (count == mList.size() && mList.size() != 0 && !isDeleteProduct) {
            mCheckAll.setSelected(true);
        } else {
            mCheckAll.setSelected(false);
        }
        isDeleteProduct = false;

        if (mList.size() == 0 || count == 0) {
            getRightView().setVisibility(View.GONE);
            if (mList.size() == 0) {
                mNoDataView.setVisibility(View.VISIBLE);
            }
        } else {
            if (!isOnlyShowProduct) {
                getRightView().setVisibility(View.VISIBLE);
            }
            mNoDataView.setVisibility(View.GONE);
        }

        mBtnClearing.setText(String.format(getString(R.string.clearing), count));
        ((TextView) getView().findViewById(R.id.total_price)).setText(String.format(
                getString(R.string.total_price), CommonUtil.transitionToFloat(getProductPrice())));
    }

    private float getProductPrice() {
        float price = 0;
        // 重新设置总计
        for (ShoppingCartInfo info : mList) {
            if (info.isChecked) {
                price += (info.goods_price * info.goods_number);
            }
        }
        return price;
    }

    @Override
    protected String getTitleName() {
        return isOnlyShowProduct ? "商品清单" : getString(R.string.shoppingcart);
    }

    @Override
    protected String getRightName() {
        return getString(R.string.delete);
    }

}
